package com.xm.web.service.impl;

import com.xm.common.entity.LoginRequest;
import com.xm.common.utils.StrPool;
import com.xm.security.utils.JwtUtil;
import com.xm.web.entity.po.TbUser;
import com.xm.web.service.LoginService;
import com.xm.web.utils.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 登录 服务实现类
 * </p>
 *
 * @author yousj
 * @since 2021-08-24
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;
    private final JwtUtil jwtUtil;

    @Override
    public TbUser login(LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        TbUser user = (TbUser) authentication.getPrincipal();
        return user.setToken(jwtUtil.createJwtToken(user.getUsername())).setPassword(StrPool.EMPTY);
    }

    @Override
    public boolean logout() {
        return jwtUtil.removeToken(SecurityUtil.getCurrentUser().getToken());
    }
}
